package cc.miwuya.property.controller;

import cc.miwuya.common.util.JwtUtils;
import cc.miwuya.common.util.Result;
import cc.miwuya.owner.domain.Orders;
import cc.miwuya.property.client.PropertyClient;
import cc.miwuya.property.client.ResidentialClient;
import cc.miwuya.property.client.UserClient;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * @Author 迷雾森林
 * @Date 2024-03-20 17:41
 */
@RestController
@RequestMapping("/property/common")
public class CommonController {
    @Resource
    PropertyClient propertyClient;
    @Resource
    HttpServletRequest httpServletRequest;
    @Resource
    ResidentialClient residentialClient;
    @Resource
    UserClient userClient;

    @GetMapping("/residentialList")
    public Result getResidentialList(){
        Long propertyId = propertyClient.getPropertyByUserid(getCurrent());
        if (propertyId==-1){
            return null;
        }
        return residentialClient.getResidentialListByPropertyId(propertyId);
    }
    /**
     * 根据管理人员获取归属物业
     */
    @GetMapping("/getResidential")
    public Result getResidential(){
        Long propertyId = propertyClient.getPropertyByUserid(getCurrent());
        if (propertyId==null){
            return Result.success();
        }
        Result info = propertyClient.info(propertyId);
        return Result.success(info.getData());
    }

    /**
     * 获取当前登录人的身份
     * @return
     */
    public Long getCurrent(){
        String authorization = httpServletRequest.getHeader("Authorization");
        Claims claim = JwtUtils.getClaimByToken(authorization, "community");
        JSON parse = JSONUtil.parse(claim);
        System.out.println(parse);
        Long username = Long.parseLong(parse.getByPath("userId").toString());
        return username;
    }
    @GetMapping("/getOrderList")
    public Result getOrderList(String name){
        return Result.success(userClient.getTollManOrderList(name,getCurrent()));
    }
    @PostMapping("/addOrder")
    public Result addOrder(@RequestBody Orders orders){
        orders.setCreated(LocalDateTime.now());
        orders.setStatus(0);
        orders.setTollman(getCurrent());
        userClient.addOrder(orders);
        return Result.success();
    }
    @GetMapping("/deleteOrder/{id}")
    public Result deleteOrder(@PathVariable Long id){
        userClient.deleteOrder(id);
        return Result.success();
    }
}
